//
//  AddViewController.m
//  footprint
//
//  Created by SongYakun on 15/12/25.
//  Copyright © 2015年 SongYakun. All rights reserved.
//

#import "AddViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface AddViewController () <UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UITextField * headField;
@property (nonatomic, strong) UITextField * moodField;
@property (nonatomic, strong) SkyButton * saveButton;
@property (nonatomic, strong) SkyButton * cancelButton;
@property (nonatomic, strong) SkyButton * addButton;

@property (nonatomic, strong) UIImagePickerController * imagePicker;

@end

@implementation AddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createTextField];
    [self createbottomButton];
    [self createImagePickerController];
}

- (void)createImagePickerController {
    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    _imagePicker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePicker.allowsEditing = YES;
}

- (void)createTextField {
    _headField = [[UITextField alloc] init];
    self.headField.delegate = self;
    self.headField.borderStyle = UITextBorderStyleRoundedRect;
    self.headField.placeholder = @"请输入标题";
    [self.view addSubview:self.headField];
    [self.headField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(50);
        make.bottom.mas_equalTo(-SCREEN_SIZE.height + 50 + 40);
        make.left.mas_equalTo(50);
        make.right.mas_equalTo(-50);
    }];
    
    _moodField = [[UITextField alloc] init];
    self.moodField.delegate = self;
    self.moodField.borderStyle = UITextBorderStyleRoundedRect;
    self.moodField.placeholder = @"请输入心情";
    [self.view addSubview:self.moodField];
    [self.moodField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.headField.mas_bottom).offset(30);
        make.bottom.mas_equalTo(-SCREEN_SIZE.height + 50 + 40 + 30 + 40);
        make.left.mas_equalTo(50);
        make.right.mas_equalTo(-50);
    }];
}

- (void)createbottomButton {
    _saveButton = [SkyButton buttonWithType:UIButtonTypeCustom];
    [self.saveButton setFrame:CGRectMake(100, 300, 80, 44) Title:@"保存" BackgroundColor:[UIColor blueColor] Image:nil andSelectedImage:nil];
    [self.saveButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.saveButton];
    
    _cancelButton = [SkyButton buttonWithType:UIButtonTypeCustom];
    [self.cancelButton setFrame:CGRectMake(200, 300, 80, 44) Title:@"取消" BackgroundColor:[UIColor blueColor] Image:nil andSelectedImage:nil];
    [self.cancelButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.cancelButton];
    
    _addButton = [SkyButton buttonWithType:UIButtonTypeCustom];
    [self.addButton setFrame:CGRectMake(200, 500, 80, 44) Title:@"添加" BackgroundColor:[UIColor redColor] Image:nil andSelectedImage:nil];
    [self.addButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addButton];
    
}

- (void)buttonClicked:(UIButton *)button {
    if (button == self.addButton) {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self selectImageFromAlbum];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                [self selectImageFromCamera];
            }else{
                NSLog(@"该设备不支持照相");
            }
        }];
        UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"录像" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                [self selectVideoFromCamera];
            }else{
                NSLog(@"该设备不支持录像");
            }
        }];
        UIAlertAction * action4 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action1];
        [alert addAction:action2];
        [alert addAction:action3];
        [alert addAction:action4];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    
}

- (void)selectImageFromAlbum {
    //NSLog(@"相册");
    _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:_imagePicker animated:YES completion:nil];
}

- (void)selectImageFromCamera {
    _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    _imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];
    _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    [self presentViewController:_imagePicker animated:YES completion:nil];

}

- (void)selectVideoFromCamera {
    _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //录制视频时长，默认10s
    _imagePicker.videoMaximumDuration = 15;
    
    //相机类型（拍照、录像...）字符串需要做相应的类型转换
    _imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];
    
    //视频上传质量
    //UIImagePickerControllerQualityTypeHigh高清
    //UIImagePickerControllerQualityTypeMedium中等质量
    //UIImagePickerControllerQualityTypeLow低质量
    //UIImagePickerControllerQualityType640x480
    _imagePicker.videoQuality = UIImagePickerControllerQualityTypeHigh;
    
    //设置摄像头模式（拍照，录制视频）为录像模式
    _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
    [self presentViewController:_imagePicker animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.headField resignFirstResponder];
    [self.moodField resignFirstResponder];
}

#pragma mark UIImagePickerControllerDelegate
//该代理方法仅适用于只选取图片时
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    NSLog(@"选择完毕----image:%@-----info:%@",image,editingInfo);
}

////适用获取所有媒体资源，只需判断资源类型
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
//    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
//    //判断资源类型
//    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//        //如果是图片
//        self.imageView.image = info[UIImagePickerControllerEditedImage];
//        //压缩图片
//        NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
//        //保存图片至相册
//        UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
//        //上传图片
//        [self uploadImageWithData:fileData];
//        
//    }else{
//        //如果是视频
//        NSURL *url = info[UIImagePickerControllerMediaURL];
//        //播放视频
//        _moviePlayer.contentURL = url;
//        [_moviePlayer play];
//        //保存视频至相册（异步线程）
//        NSString *urlStr = [url path];
//        
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
//                
//                UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
//            }
//        });
//        NSData *videoData = [NSData dataWithContentsOfURL:url];
//        //视频上传
//        [self uploadVideoWithData:videoData];
//    }
//    [self dismissViewControllerAnimated:YES completion:nil];
//}

#pragma mark 图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{
    
}

#pragma mark 视频保存完毕的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
    if (error) {
        NSLog(@"保存视频过程中发生错误，错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
